<?php
namespace app\admin\controller;

use think\Cache;
use think\Session;
use think\Db;
use think\Image;
use think\Log;
use OSS\OssClient;
use OSS\Core\OssException;
use app\service\Token;

class Kaitest
{
    //补充特定时间段内平级合伙人的用户充值的2% （3级之内）
    public function index()
    {
        return '程序执行过了';
        $startTime = '2025-05-25 15:54:00';
        $endTime = '2025-05-26 03:45:00';

        // 初始化统计数据
        $result = [
            'total_users' => 0,           // 总处理用户数
            'success_users' => 0,         // 成功分配佣金用户数
            'total_partners' => 0,        // 总合伙人受益数
            'total_commission' => 0.00,   // 总佣金金额
            'errors' => []                // 错误信息
        ];

        $userRechargeData = Db::name('topup')
            ->where('addtime', '>=', $startTime)
            ->where('addtime', '<=', $endTime)
            ->where('state', 1)
            ->group('fk_userid')
            ->order('fk_userid', 'desc')
            ->field('fk_userid, SUM(money) as total_amount')
            ->select();

        $result['total_users'] = count($userRechargeData);

        // 遍历充值统计结果
        foreach ($userRechargeData as $userData) {
            try {
                $userId = $userData['fk_userid'];
                $totalAmount = $userData['total_amount'];
                $commissionRate = 0.02;

                $currentUser = Db::name('user')->where('id', $userId)->find();
                if (empty($currentUser)) {
                    $this->logAction("充值用户ID={$userId} 不存在，跳过处理");
                    $result['errors'][] = "用户ID={$userId} 不存在";
                    continue;
                }

                $partners = [];
                $currentInviterCode = $currentUser['yqr'];
                $visitedCodes = [];

                while (!empty($currentInviterCode) && count($partners) < 2 && !in_array($currentInviterCode, $visitedCodes)) {
                    $visitedCodes[] = $currentInviterCode;

                    $inviter = Db::name('user')
                        ->where('yqm', $currentInviterCode)
                        ->field('id, yqr, level, score, name')
                        ->find();

                    if (empty($inviter)) break;

                    if ($inviter['level'] == 3) {
                        $partners[] = $inviter;
                    }

                    $currentInviterCode = $inviter['yqr'];
                }

                if (empty($partners)) {
                    $this->logAction("充值用户 {$currentUser['name']}({$userId}) 无符合条件的合伙人上级");
                    continue;
                }

                $successPartnerCount = 0;
                $userCommissionTotal = 0;

                foreach ($partners as $partner) {
                    $commission = $totalAmount * $commissionRate;
                    $newScore = $partner['score'] + $commission;
                    Db::startTrans();
                    try {
                        Db::name('yaoqing_records')->insert([
                            'uid'        => $partner['id'],
                            'touid'      => $userId,
                            'source_uid' => $userId,
                            'content'    => "{$currentUser['name']}({$userId})充值 平级奖励(补发.)",
                            'money'      => $commission,
                            'time'       => time(),
                            'type'       => 1,
                            'data'       => 0,
                            'order_id'   => '',
                            'balance'    => $newScore,
                            'show_money' => $commission
                        ]);

                        Db::name('user')
                            ->where('id', $partner['id'])
                            ->setInc('score', $commission);

                        Db::commit();

                        $this->logAction("充值用户 {$currentUser['name']}({$userId}) 为合伙人 {$partner['name']}({$partner['id']}) 贡献积分 {$commission}，原积分 {$partner['score']}，现积分 {$newScore}");

                        $successPartnerCount++;
                        $userCommissionTotal += $commission;
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->logAction("分配佣金失败：用户ID={$userId}，合伙人ID={$partner['id']}，错误：{$e->getMessage()}", true);
                        $result['errors'][] = "用户ID={$userId} 给 合伙人ID={$partner['id']} 分配佣金失败：{$e->getMessage()}";
                    }
                }

                if ($successPartnerCount > 0) {
                    $result['success_users']++;
                    $result['total_partners'] += $successPartnerCount;
                    $result['total_commission'] += $userCommissionTotal;
                }

            } catch (\Exception $e) {
                $this->logAction("处理用户ID={$userId} 时发生未知错误：{$e->getMessage()}", true);
                $result['errors'][] = "处理用户ID={$userId} 时发生未知错误：{$e->getMessage()}";
            }
        }

        // 返回处理结果
        return json([
            'code' => 200,
            'message' => '佣金分配处理完成',
            'data' => $result,
            'log_path' => realpath(__DIR__ . '/hhrlog_new.txt')
        ]);
    }

    /**
     * 记录操作日志到文件
     * @param string $message 日志内容
     * @param bool $isError 是否为错误日志
     */
    private function logAction($message, $isError = false) {
        $logTime = date('Y-m-d H:i:s');
        $logLevel = $isError ? 'ERROR' : 'INFO';
        $logContent = "[{$logTime}] [{$logLevel}] {$message}\n";

        // 写入日志文件
        file_put_contents(
            __DIR__ . '/hhrlog_new.txt',
            $logContent,
            FILE_APPEND | LOCK_EX
        );
    }
}